

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using JTC.MiniCommerce.Core;
using JTC.MiniCommerce.Store;
using JTC.MiniCommerce.Store.Services.ShippingService;
using JTC.MiniCommerce.Store.Services.CouponService;
using SubSonic.Utilities;
using JTC.MiniCommerce.Localization;

namespace JTC.MiniCommerce.Web {
  public partial class paypalcheckout : System.Web.UI.Page {
    
    #region Member Variables
    
    private Order order;
    
    #endregion
    
    #region Page Events

    /// <summary>
    /// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event to initialize the page.
    /// </summary>
    /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
    protected override void OnInit(EventArgs e) {
      order = new OrderController().FetchOrder(WebUtility.GetUserName());
      
      Label lblShippingInformation = acCheckout.Panes[0].FindControl("lblShippingInformation") as Label;
      Label lblShippingMethod = acCheckout.Panes[1].FindControl("lblShippingMethod") as Label;
      Label lblCouponInformation = acCheckout.Panes[2].FindControl("lblCouponInformation") as Label;
      Label lblOrderReview = acCheckout.Panes[3].FindControl("lblOrderReview") as Label;
  

      LocalizationUtility.AddLabelText(lblShippingInformation);
      LocalizationUtility.AddLabelText(lblShippingMethod);
      LocalizationUtility.AddLabelText(lblOrderReview);
      LocalizationUtility.AddLabelText(lblShippingAddressTitle);
      LocalizationUtility.AddLabelText(lblShippingMethodTitle);
      LocalizationUtility.AddLabelText(lblCouponInformation);
      LocalizationUtility.AddLabelText(lblCouponInformationTitle);
      LocalizationUtility.AddLabelText(lblCouponCode);
     
      btnShippingAddress.Text = LocalizationUtility.GetText("lblContinue");
      btnShippingMethod.Text = LocalizationUtility.GetText("lblContinue");
      btnCoupon.Text = LocalizationUtility.GetText("lblContinue");
      
      LocalizationUtility.AddButtonText(btnProcessOrder);
      btnProcessOrder.Enabled = false;
      base.OnInit(e);
    }

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e) {
      try {
        orderSummary.Order = order;
        //this.btnProcessOrder.Attributes.Add("onclick", string.Format("this.value='{0}';this.disabled = true;" + Page.ClientScript.GetPostBackEventReference(this.btnProcessOrder, ""), LocalizationUtility.GetText("lblPleaseWait")));
        this.btnProcessOrder.Attributes.Add("onclick", "this.disabled = true;" + Page.ClientScript.GetPostBackEventReference(this.btnProcessOrder, ""));

        if (!Page.IsPostBack) {
          SetShipToAddressDisplay();
          SetShippingMethodDisplay();
          //SetCouponDisplay();
        }
      }
      catch (Exception ex) {
        Logger.Error(typeof(paypalcheckout).Name + ".Page_Load", ex);
        throw;
      }
    }

    /// <summary>
    /// Handles the PreRender event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Page_PreRender(object sender, EventArgs e) {
      upDisplay.ProgressTemplate = new OrderProgressTemplate();
    }

    /// <summary>
    /// Handles the Click event of the btnShippingAddress control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnShippingAddress_Click(object sender, EventArgs e) {
      try {
        Address address = new Address();
        if(!shippingAddress.NewAddressPanel.Visible) {
          Guid selectedAddress = new Guid(shippingAddress.AddressList.SelectedValue);
          address = WebProfile.Current.AddressCollection.Find(delegate(Address addressToFind) {
            return addressToFind.AddressId == selectedAddress && addressToFind.AddressType == AddressType.ShippingAddress;
          });
        }
        else {
          if(!string.IsNullOrEmpty(shippingAddress.AddressId)) { //They are editing an existing address
            Guid selectedAddress = new Guid(shippingAddress.AddressId);
            address = WebProfile.Current.AddressCollection.Find(delegate(Address addressToFind) {
              return addressToFind.AddressId == selectedAddress && addressToFind.AddressType == AddressType.ShippingAddress;
            });
            if(address.AddressId != Guid.Empty) {
              //go ahead and remove it - we are just going to add it with the updated info
              WebProfile.Current.AddressCollection.Remove(address);
            }
          }
          address.FirstName = shippingAddress.FirstName;
          address.LastName = shippingAddress.LastName;
          address.Phone = shippingAddress.Phone;
          address.Email = shippingAddress.Email;
          address.Address1 = shippingAddress.Address1;
          address.Address2 = shippingAddress.Address2;
          address.City = shippingAddress.City;
          address.StateOrRegion = shippingAddress.StateOrRegion;
          address.PostalCode = shippingAddress.PostalCode;
          address.Country = shippingAddress.Country;
          address.UserName = WebUtility.GetUserName();
          address.AddressType = AddressType.ShippingAddress;
          WebProfile.Current.AddressCollection.Add(address);
          WebProfile.Current.Save();
          //set the id so we can get it to determine if it's an edit or not
          shippingAddress.AddressId = address.AddressId.ToString();
        }
        order.ShipToAddress = address.ToXml();
        order.Save(WebUtility.GetUserName());
        shippingAddressDisplay.Address = address;
        shippingAddressDisplay.DisplayAddress();
        GetShippingRates();
      }
      catch(Exception ex) {
        Logger.Error(typeof(paypalcheckout).Name + ".btnShippingAddress_Click", ex);
        throw;
      }      
    }

    /// <summary>
    /// Handles the Click event of the btnShippingMethod control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnShippingMethod_Click(object sender, EventArgs e) {
      try {
        decimal shippingAmount = 0;
        decimal.TryParse(rblShippingOptions.SelectedValue, out shippingAmount);
        OrderController.SetShipping(WebUtility.GetUserName(), shippingAmount, rblShippingOptions.SelectedItem.Text);
        OrderController.CalculateTax(WebUtility.GetUserName());
        lblShippingMethodDisplay.Text = rblShippingOptions.SelectedItem.Text;
        //re-load the order
        order = new OrderController().FetchOrder(WebUtility.GetUserName());
        orderSummary.Order = order; 
        orderSummary.LoadOrder();       
      }
      catch(Exception ex) {
        Logger.Error(typeof(paypalcheckout).Name + ".btnShippingMethod_Click", ex);
        throw;
      }
    }

    /// <summary>
    /// Handles the Click event of the btnCoupon control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnCoupon_Click(object sender, EventArgs e) {
      try {
        if(!string.IsNullOrEmpty(txtCouponCode.Text)) {
          CouponService couponService = new CouponService();
          couponService.ApplyCoupon(txtCouponCode.Text, order);
          lblCouponInformationDisplay.Text = StoreUtility.GetFormattedAmount(order.DiscountAmount, true);
          //re-load the order
          order = new OrderController().FetchOrder(WebUtility.GetUserName());
          orderSummary.Order = order;
          orderSummary.LoadOrder();       
        }
        else {
          lblCouponInformationDisplay.Text = StoreUtility.GetFormattedAmount(0.00M, true);
        }        
        btnProcessOrder.Enabled = true;        
      }
      catch(Exception ex) {
        Logger.Error(typeof(paypalcheckout).Name + ".btnCoupon_Click", ex);
        throw;
      }
    }

    /// <summary>
    /// Handles the Click event of the btnProcessOrder control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnProcessOrder_Click(object sender, EventArgs e) {
      try {
        order.IPAddress = Request.UserHostAddress;
        order.Save(WebUtility.GetUserName());
        
        string returnUrl = Utility.GetSiteRoot() + "/paypal/pdthandler.aspx";
        string cancelUrl = Utility.GetSiteRoot() + "/paypalcheckout.aspx";
        
        string url = OrderController.CreateCartUrl(order, returnUrl, cancelUrl);
        if(!string.IsNullOrEmpty(url)) {
          Response.Redirect(url, true);
        }
      }
      catch(Exception ex) {
        Logger.Error(typeof(paypalcheckout).Name + ".btnProcessOrder_Click", ex);
        throw;
      }
    }

    #endregion

    #region Private Methods

    /// <summary>
    /// Sets the ship to address display.
    /// </summary>
    private void SetShipToAddressDisplay() {
      if(!string.IsNullOrEmpty(order.ShipToAddress)) {
        shippingAddressDisplay.Address = order.ShippingAddress;
        shippingAddress.SelectedAddress = order.ShippingAddress.AddressId.ToString();
        cpeShippingAddressDisplay.Collapsed = false;
        acCheckout.SelectedIndex = acCheckout.SelectedIndex + 1;
        GetShippingRates();
      }
    }

    /// <summary>
    /// Sets the shipping method display.
    /// </summary>
    private void SetShippingMethodDisplay() {
      if(!string.IsNullOrEmpty(order.ShippingMethod)) {
        lblShippingMethodDisplay.Text = order.ShippingMethod;
        cpeShippingMethodDisplay.Collapsed = false;
        acCheckout.SelectedIndex = acCheckout.SelectedIndex + 1;
      }
    }

    /// <summary>
    /// Sets the coupon display.
    /// </summary>
    private void SetCouponDisplay() {
      if (order.DiscountAmount > 0) {
        lblCouponInformationDisplay.Text = StoreUtility.GetFormattedAmount(order.DiscountAmount, true);
        cpeCouponInformationDisplay.Collapsed = false;
        acCheckout.SelectedIndex = acCheckout.SelectedIndex + 1;
      }
    }

    /// <summary>
    /// Gets the shipping rates.
    /// </summary>
    private void GetShippingRates() {
      ShippingOptionCollection shippingOptionCollection = OrderController.FetchShippingOptions(WebUtility.GetUserName());
      ListItem listItem;
      rblShippingOptions.Items.Clear();
      foreach(ShippingOption shippingOption in shippingOptionCollection) {
        listItem = new ListItem(string.Format("{0}: {1}", shippingOption.Service, StoreUtility.GetFormattedAmount(shippingOption.Rate, true)), shippingOption.Rate.ToString());
        rblShippingOptions.Items.Add(listItem);
      }
      if(order.ShippingAmount > 0) {
        ListItem selectedItem = rblShippingOptions.Items.FindByValue(order.ShippingAmount.ToString());
        if(selectedItem != null) {
          selectedItem.Selected = true;
        }
        else {
          rblShippingOptions.SelectedIndex = 0;
        }
      }
      else {
        rblShippingOptions.SelectedIndex = 0;
      }
    }
       
    #endregion 
    
  }
}
